<?php
declare (strict_types=1);

namespace app\index\controller;

use addons\V2\admin\model\ProductCate;
use app\common\model\Carousel;
use think\facade\Cache;
use think\facade\View;

class Index extends Base
{

    /**
     * 授权中转页
     */
    public function transfer()
    {
        try {
            if (is_weixin()) {
                $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . '/index/index/oauth.html';
                $result = \WeChat\Oauth::instance(config('pay')['wechat'])->getOauthRedirect($redirect_url);
                return redirect($result);
            } else {
                return redirect('/');
            }
        } catch (\Exception $e) {
            return redirect('/');
        }

    }

    /**
     * @return \think\response\Redirect
     * 根据code 获取openid，并且更改，随后跳转回首页
     */
    public function oauth()
    {
        try {
            $param = $this->request->param();
            if (isset($param['code'])) {
                $result = \WeChat\Oauth::instance(config('pay')['wechat'])->getOauthAccessToken($param['code']);
                if ($result['openid']) {
                    $this->user->openid = $result['openid'];
                    $this->user->save();
                }
            }
            return redirect('/');
        } catch (\Exception $e) {
            return redirect('/');
        }
    }


    public function index()
    {
        View::assign([
            'carousel' => Carousel::getList(),
            'cate'     => ProductCate::where(['status' => 1,'pid' => 0])->select()
        ]);
        return View::fetch();
    }

    public function communal()
    {
        $type = $this->request->param('type');
        $title = [ 'privacy_msg' => '注册协议'];

        View::assign([
            'title'   => $title[$type],
            'content' => Cache::get('system')[$type]
        ]);
        return View::fetch();
    }
}
